#!/bin/sh

set -eu
#set -x

PACKAGE='gmb'

prefix="${HOME}/local"

bindir="${prefix}/bin"
libexecdir="${prefix}/libexec"
pkglibexecdir="${libexecdir}/${PACKAGE}"
sysconfdir="${prefix}/etc"
pkgsysconfdir="${sysconfdir}/${PACKAGE}"

SHELL='/bin/dash'

TOP_SRCDIR=$(realpath $(dirname "${0}"))

BUILDDIR="${TOP_SRCDIR}/.build"

BIN_SRCDIR="${TOP_SRCDIR}/bin"
LIB_SRCDIR="${TOP_SRCDIR}/lib"
DRIVERS_SRCDIR="${TOP_SRCDIR}/drivers"


message() { echo "setup: ${@}"; }
error()   { error_nf "${@}"; exit 1; }


list_modules()
{
    local dir="${1}"
    local wd=$(pwd)
    cd "${dir}"
    find -name '*.in' | sed -e 's,^\./,,g; s,\.in$,,g'
    cd "${wd}"
}


get_subst_expr()
{
    local subst_vars="\
PACKAGE
prefix
pkglibexecdir
pkgsysconfdir
SHELL
"
    for var in ${subst_vars}; do
        local val=$(eval "echo \${${var}}")
        printf "s,@${var}@,${val},g; "
    done
}


SUBST_EXPR=$(get_subst_expr)


build_module()
{
    local src="${1}"
    local dst="${2}"
    local dstdir=$(dirname "${dst}")

    [ -d "${dstdir}" ] || mkdir -vp "${dstdir}"
    if [ -f "${dst}" -a "${src}" -ot "${dst}" ]; then
        true #echo "gmb: - ${dst}"
    else
        echo "gmb: U ${dst} <- ${src}"
        sed -e "${SUBST_EXPR}" "${src}" >"${dst}.tmp"
        mv -f "${dst}.tmp" "${dst}"
    fi
}


proc_build()
{
    message "build"
    
    # message "BIN_MODULES:" ${BIN_MODULES}
    # message "LIB_MODULES:" ${LIB_MODULES}
    # message "DRIVERS_MODULES:" ${DRIVERS_MODULES}

    for module in ${BIN_MODULES}; do
        build_module "${BIN_SRCDIR}/${module}.in" "${BUILDDIR}/bin/${module}"
    done

    for module in ${LIB_MODULES}; do
        build_module "${LIB_SRCDIR}/${module}.in" "${BUILDDIR}/lib/${module}"
    done

    for module in ${DRIVERS_MODULES}; do
        build_module "${DRIVERS_SRCDIR}/${module}.in" "${BUILDDIR}/drivers/${module}"
    done
}


install_module()
{
    local mode="${1}"
    local src="${2}"
    local dst="${3}"

    rm -f "${3}"
    install -v -D -m${mode} "${src}" "${dst}"
}


proc_install()
{
    message "install"

    for module in ${BIN_MODULES}; do
        install_module 755 "${BUILDDIR}/bin/${module}" "${bindir}/${module}"
    done

    for module in ${LIB_MODULES}; do
        install_module 644 "${BUILDDIR}/lib/${module}" "${pkglibexecdir}/${module}"
    done

    for module in ${DRIVERS_MODULES}; do
        if [ x"${module%.conf}" = x"${module}" ]; then
            install_module 755 "${BUILDDIR}/drivers/${module}" "${pkglibexecdir}/drivers/${module}"
        else
            install_module 644 "${BUILDDIR}/drivers/${module}" "${pkglibexecdir}/drivers/${module}"
        fi
    done
}


main()
{
    BIN_MODULES=$(list_modules "${BIN_SRCDIR}")
    LIB_MODULES=$(list_modules "${LIB_SRCDIR}")
    DRIVERS_MODULES=$(list_modules "${DRIVERS_SRCDIR}")

    ALL_MODULES="${BIN_MODULES} ${LIB_MODULES} ${DRIVERS_MODULES}"
    
    cd "${TOP_SRCDIR}"
    
    proc_build
    proc_install
    message "all done!"
}


#
main ${@}
